package com.coderman.daoclient.connections;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by ${fanchunshuai} on 2017-7-26.
 *
 * @author 58
 * @version: V1.0
 * @Desc:
 * @Copyright (c) 2017 58到家-版权所有
 */
public class ConnectionPool {
    private  DBConfig dbConfig = new DBConfig();
    private  SimpleDataSource simpleDataSource = new SimpleDataSource(dbConfig);
    private  LinkedBlockingDeque<Connection> connectionList = new LinkedBlockingDeque<>();
    private  volatile  boolean isInit = false;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取连接
     * @return
     */
    public synchronized Connection getConnection(){
        if(!isInit || connectionList.isEmpty()){
            isInit = true;
            try {
                System.out.println("init times, isInit = "+isInit+",connectionList = "+connectionList.size());
                init();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        System.out.println("当前链接数="+connectionList.size());
        return connectionList.pollFirst();
    }

    /**
     * 初始化连接池
     * @throws SQLException
     */
    private void init() throws SQLException {
        int minPoolSize = Integer.parseInt(dbConfig.getMinPoolSize());

        for (int i = 0 ;i < minPoolSize;i++){
            connectionList.add(simpleDataSource.createConnection());
        }
    }

    /**
     * 将连接返回连接池
     * @param connection
     */
    public void free(Connection connection){
        connectionList.add(connection);
    }

    public static void main(String[] args) {
        ConnectionPool connectionPool = new ConnectionPool();
        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());

        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());
        System.out.println(connectionPool.getConnection().toString());

    }

}
